import os
from flask import Flask, url_for, render_template, Blueprint
from flask_sqlalchemy import SQLAlchemy
from easyRead.api import bp as api_bp
from easyRead.extensions import db
from easyRead.extensions import cors, db, migrate
import easyRead.config

def create_app(config_class=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.secret_key = "secret key"

    # #加载配置文件
    # app.config.from_object('config')

    # 初始化数据库连接
    app.config.from_object(easyRead.config)

    # Initialization flask app
    configure_app(app, config_class)
    configure_blueprints(app)
    configure_extensions(app)
    # 不使用 Jinja2，用不到模版过滤器和上下文处理器
    # configure_template_filters(app)
    # configure_context_processors(app)
    configure_before_handlers(app)
    configure_after_handlers(app)
    configure_errorhandlers(app)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass


    # a simple page that says hello
    @app.route('/hello')
    def hello():
        print("hello")
        db.drop_all()
        db.create_all()
        db.session.commit()
        return 'Hello, World!'



    # with app.app_context():
    #     db.drop_all()
    #     db.create_all()
    #     db.session.commit()
    # 导入蓝图
    # from easyRead.user_lend import user_lend_blueprint
    # app.register_blueprint(user_lend_blueprint)

    # with app.test_request_context():

    return app

def configure_app(app, config_class):
    app.config.from_object(config_class)
    # 不检查路由中最后是否有斜杠/
    app.url_map.strict_slashes = False


def configure_blueprints(app):
    # 注册 blueprint
    app.register_blueprint(api_bp, url_prefix='/api')


def configure_extensions(app):
    '''Configures the extensions.'''
    # Enable CORS
    cors.init_app(app)
    # Init Flask-SQLAlchemy
    db.init_app(app)
    # Init Flask-Migrate
    migrate.init_app(app, db)
    # Init Flask-Mail


def configure_before_handlers(app):
    '''Configures the before request handlers'''
    pass


def configure_after_handlers(app):
    '''Configures the after request handlers'''
    pass


def configure_errorhandlers(app):
    '''Configures the error handlers'''
    pass
